package com.mengxuegu.security.authrntication;

import com.mengxuegu.base.result.MengxueguResult;
import com.mengxuegu.security.properites.LoginResponseType;
import com.mengxuegu.security.properites.SecurityProperties;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 处理失败认证
 * @author william
 * @create 2021-07-03 23:12
 **/
@Component("customAuthenticationFailureHandler")
//public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    Logger logger= LoggerFactory.getLogger(CustomAuthenticationFailureHandler.class);

    @Autowired
    private SecurityProperties securityProperties;
    /**
     *
     * @param request
     * @param response
     * @param exception
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

      if(LoginResponseType.JSON.equals(securityProperties.getAuthentication().getLoginType())){
          //认证失败后,响应json 字符串
          MengxueguResult result = MengxueguResult.build(HttpStatus.UNAUTHORIZED.value(),exception.getMessage());

          String json = result.toJsonString();
          response.setContentType("application/json;charset=UTF-8");
          response.getWriter().write(json);
      }else{
          //
//          super.setDefaultFailureUrl(securityProperties.getAuthentication().getLoginPage()+"?error");
          //获取上一次请求路径
          String referer = request.getHeader("Referer");
          logger.info("referer:"+referer);
          //如果toAuthentication 有值,则认为是多端登录,直接返回一个登录页面
          Object toAuthentication = request.getAttribute("toAuthentication");
          String lastUrl = toAuthentication !=null ?securityProperties.getAuthentication().getLoginPage() : StringUtils.substringBefore(referer, "?");
          logger.info("lastUrl:"+lastUrl);
          super.setDefaultFailureUrl(lastUrl+"?error");
          super.onAuthenticationFailure(request,response,exception);
      }

    }
}
